<?php

/**
 * 载入缓存处理类
 */
require('sync/cache.php');

/**
 * 生成同步脚本
 *
 * @author    Y.N
 * @update	2011/5/12
 */
class CLI_Make extends CLI
{
    protected $_page_size = 10;

	/**
	 * CLI主方法
	 *
	 * @param	none
	 * @access	public
	 * @return	void
	 * @update	2011/4/19
	*/
	public function main()
	{
		// 获取子叶类目缓存
		$date = date("Ymd");
		$Sync_Cache = new Sync_Cache();
		$data = $Sync_Cache->get_cache('rootcats_'.$date);
		$root_cats = json_decode($data);

		if (empty($root_cats))
		{
		    $root_cats = self::get_root_cats();
			$Sync_Cache->save_cache('rootcats_'.$date, json_encode($root_cats));
		}

		// 类目的页数
		$total_page = ceil(count($root_cats)/$this->_page_size);

		// 生成shell文件
		$path = BASEPATH;
		$file = $path."/synctb.sh";

		$content = "";
		if ( ! file_exists($file))
		{
			for ($i=1; $i<=$total_page; $i++)
			{
				$content .= $path."/cli sputb --page=".$i."\n\n";
			}
			file_put_contents($file, $content);
		}

		//自动清除两天前的缓存
		$Sync_Cache->auto_clear_cache();

	} // end func


	/**
	 * 获取360hqb子叶类目
	 *
	 * @param	int $parent_cid
	 * @access	public
	 * @return	array
	 * @update	2011/3/22
	*/
	public static function get_root_cats($parent_cid = 0)
	{
		$root_cats = array();

		$item_cats = DB::select('cid')
			->from('item_cats')
			->where('parent_cid', '=',$parent_cid)
			->fetch_all();

		if ($item_cats)
		{
			foreach ($item_cats as $key => $value)
			{
				$root_cats = array_merge($root_cats,self::get_root_cats($value['cid']));
			}
		}else {
			$root_cats[] = $parent_cid;
		}
		return $root_cats;
	} // end func

} // end class


